package com.huitone.gddw.controller.worktable.paramconfigmanage;

import com.huitone.gddw.common.excel.CreateExcel;
import com.huitone.gddw.controller.common.CommonController;
import com.huitone.gddw.dao.entity.GateDef;
import com.huitone.gddw.dao.entity.SmLog;
import com.huitone.gddw.dao.entity.SvrRouteRule;
import com.huitone.gddw.model.support.Message;
import com.huitone.gddw.model.support.QueryPage;
import com.huitone.gddw.service.IGateDefService;
import com.huitone.gddw.service.ISvrRouteRuleService;
import com.huitone.gddw.service.dto.GateDefDTO;
import com.huitone.gddw.utils.SysLoginUtil;
//import com.sun.tools.classfile.Annotation.element_value; 不知道为什么报错,先注释掉,, 注释掉能正常启动起来  
//import com.sun.tools.javac.code.Attribute.Array;

import oracle.sql.ARRAY;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 短信网关通道管理控制器
 * @author wuluodan
 *
 */
@Controller
@RequestMapping(value="gateDef")
public class GateDefController extends CommonController {

	private final static Logger LOGGER = Logger.getLogger(GateDefController.class);
	
	@Autowired
	private IGateDefService gateDefService;
	
	@Autowired
	private ISvrRouteRuleService svrRouteRuleService;
	
	/**
	 * 短信网关通道管理查询
	 * @param page
	 * @param request
	 * @return QueryPage
	 */
	@ResponseBody
	@RequestMapping(value="query")
	public QueryPage<GateDefDTO> query(QueryPage<GateDef> page, HttpServletRequest request) {
		super.logType = SmLog.LOGTYPE_SELECT;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]查询短信网关通道";
		Map<String, Object> params = new HashMap<String, Object>();
		String gateLinkId = request.getParameter("gateLinkId");
		String status = request.getParameter("status");
		params.put("gateLinkId", gateLinkId);
		params.put("status", status);
		page.setParams(params);
		QueryPage<GateDefDTO> result = null;
		try {
			result = gateDefService.selectPage(page);
		} catch (Exception e) {
			LOGGER.error("查询短信类型信息出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return result;
	}
	
	/**
	 * 获取短信通道信息
	 * @return gateLinkId gateLinkName
	 */
	@ResponseBody
	@RequestMapping(value="getGateLink")
	public List<Map<String, Object>> getGateLink(String status,String gateLinkName) {
		List<Map<String, Object>> list = gateDefService.getGateLink(status,gateLinkName);
		return list;
	}
	
	/**
	 * 根据业务类型获取未被设置的短信通道信息
	 * @return gateLinkId gateLinkName
	 */
	@ResponseBody
	@RequestMapping(value="getUnusedGateByService")
	public List<Map<String, Object>> getNotSetGateByService(String serviceCode) {
		List<Map<String, Object>> listUnused = new ArrayList<Map<String, Object>>();
		List<String> listId = svrRouteRuleService.getGateIdByService(serviceCode);
		List<Map<String, Object>> listGate = gateDefService.getGateLink("","");
		for (Map<String, Object> map : listGate) {
			if (!listId.contains(map.get("GATE_LINK_ID"))) {
				listUnused.add(map);
			}
		}
		return listUnused;
	}
	
	/**
	 * 更改短信网关通道状态
	 * @param gateLinkId 短信通道ID
	 * @param status 更改后状态
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="changeStatus")
	public Message changeStatus(String gateLinkId, String status) {
		try {
			GateDef entity = gateDefService.selectByPrimaryKey(gateLinkId);
			entity.setStatus(status);
			gateDefService.update(entity);
			return new Message(true, "操作成功！");
		} catch (Exception e) {
			LOGGER.error("更改短信网关通道状态过程中出现异常：" + e.getMessage(), e);
			return new Message(false, "操作失败！");
		}
	}
	
	/**
	 * 修改页面数据准备
	 * @param gateLinkId 短信通道ID
	 * @return GateDefDTO
	 */
	@ResponseBody
	@RequestMapping(value="toUpdate")
	public GateDefDTO toUpdate(String gateLinkId) {
		try {
			GateDefDTO entity = gateDefService.toUpdate(gateLinkId);
			return entity;
		} catch (Exception e) {
			LOGGER.error("跳转修改页面过程中出现异常：" + e.getMessage(), e);
			return new GateDefDTO();
		}
	}
	
	/**
	 * 保存短信网关通道信息
	 * @param entity GateDef
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="save")
	public Message save(GateDef entity) {
		super.logType = SmLog.LOGTYPE_UPDATE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]添加短信网关通道";
		boolean isSuccess = true;
		String msg;
		try {
			List<Map<String, Object>> list = gateDefService.getGateLinkByGateLinkName(entity.getGateLinkName());
			if (list.size()>0) {
				isSuccess = false;
				msg = "短信通道名称有重复，请重新设置！";
			}else {
				gateDefService.save(entity);
				msg = "保存成功！";
			}
		} catch (Exception e) {
			LOGGER.error("保存短信网关通道信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "保存失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 更新短信网关通道信息
	 * @param entity GateDef
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="update")
	public Message update(GateDef entity) {
		super.logType = SmLog.LOGTYPE_UPDATE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]修改短信网关通道";
		boolean isSuccess = true;
		String msg;
		try {
			GateDef gateDef = gateDefService.selectByPrimaryKey(entity.getGateLinkId());
			gateDef.setGateLinkName(entity.getGateLinkName());
			gateDef.setSpNumber(entity.getSpNumber());
			gateDef.setCorpId(entity.getCorpId());
			gateDef.setLinkNum(entity.getLinkNum());
			gateDef.setStatus(entity.getStatus());
			gateDef.setSpecialIp(entity.getSpecialIp());
			gateDef.setSpecialPort(entity.getSpecialPort());
			gateDef.setSpecialLoginUser(entity.getSpecialLoginUser());
			gateDef.setSpecialLoginPwd(entity.getSpecialLoginPwd());
			gateDef.setInternetIp(entity.getInternetIp());
			gateDef.setInternetPort(entity.getInternetPort());
			gateDef.setInternetLoginUser(entity.getInternetLoginUser());
			gateDef.setInternetLoginPwd(entity.getInternetLoginPwd());
			gateDef.setServerIp(entity.getServerIp());
			gateDef.setServerPort(entity.getServerPort());
			gateDef.setLoginUser(entity.getLoginUser());
			gateDef.setLoginPwd(entity.getLoginPwd());
			gateDef.setMobileCorp(entity.getMobileCorp());
			gateDef.setDesc(entity.getDesc());
			gateDef.setSignType(entity.getSignType());
			gateDef.setMaxFlow(entity.getMaxFlow());
			
			List<Map<String, Object>> list = gateDefService.getGateLinkByGateLinkName(entity.getGateLinkName());
			if (list.size()>1) {
				isSuccess = false;
				msg = "短信通道名称有重复，请重新设置！";
			}else {
				gateDefService.update(gateDef);
				msg = "修改成功！";
			}
		} catch (Exception e) {
			LOGGER.error("修改短信网关通道信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "修改失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 删除短信网关通道信息
	 * @param gateLinkId 短信通道ID
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="delete")
	public Message delete(String gateLinkId) {
		super.logType = SmLog.LOGTYPE_DELETE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]删除禁发时段规则";
		boolean isSuccess = true;
		String msg;
		try {
			List<SvrRouteRule> list = svrRouteRuleService.getByGateLinkId(gateLinkId);
			if (!list.isEmpty() || list.size() > 0) {
				super.logResult = SmLog.RESULT_FAIL;
				isSuccess = false;
				msg = "该短信通道已被业务路由引用，无法删除！";
			} else {
				gateDefService.delete(gateLinkId);
				msg = "删除成功！";
			}
		} catch (Exception e) {
			LOGGER.error("删除短信网关通道信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "删除失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 发送规则
	 * @param gateLinkId 通道ID
	 * @param provinces 省份集
	 * @param mobilCorps 运营商集
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="changeLinkSend")
	public Message changeLinkSend(String gateLinkId, String provinces, String mobilCorps) {
		try {
			gateDefService.changeLinkSend(gateLinkId, provinces, mobilCorps);
			return new Message(true, "操作成功！");
		} catch (Exception e) {
			LOGGER.error("更新发送规则过程中出现异常：" + e.getMessage(), e);
			return new Message(false, "操作失败！");
		}
	}
	
	/**
	 * 导出 Excel
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/out-excel", method=RequestMethod.POST)
	public void outExcel(HttpServletRequest request, HttpServletResponse response) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "短信网关通道信息表";
		
		Map<String, Object> params = new HashMap<String, Object>();
		for (Object name : request.getParameterMap().keySet()) {
			params.put(name.toString(), request.getParameter(name.toString()));
		}
		
		List<GateDefDTO> list = gateDefService.getRecord(params);
		if (null == list || 0 == list.size()) {
			list.add(new GateDefDTO());
		}
		
		HSSFWorkbook wb = (HSSFWorkbook)CreateExcel
				.getInstance()
				.CreateNewExcelNoTemplate(fileName, list).getWorkbook();
		OutputStream fOut = null;
		try {
			fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename="+fileName+sdf.format(new Date())+".xls");
			fOut = response.getOutputStream();
			wb.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
	}

	/**
	 * 路由设置
	 * @param serviceCodes
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="updateRoute")
	public Message updateRoute(String[] serviceCodes, String gateLinkId) {
		super.logType = SmLog.LOGTYPE_UPDATE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]更新短信网关通道路由设置";
		boolean isSuccess = true;
		String msg;
		List<String> codes = Arrays.asList(serviceCodes);
		List<String> list = new ArrayList<>();
		try {
			List<SvrRouteRule> routeRules = svrRouteRuleService.getByGateLinkId(gateLinkId);
			for(SvrRouteRule routeRule:routeRules){
				//判断当前的数据库中的code在不在需要更新的列表code里面
				if (codes.contains(routeRule.getServiceCode())) {
					//在的话判断是否是第2优先级，是的话更新为第一优先级
					if("2".equals(routeRule.getRouteLevel())){
						routeRule.setRouteLevel("1");
						svrRouteRuleService.update(routeRule);
					}
					list.add(routeRule.getServiceCode());
				}else {
					//不在的话先判断routeRule是第几优先级，第1优先级的话需要删除
					if("1".equals(routeRule.getRouteLevel())){
						svrRouteRuleService.delete(routeRule.getRuleId());
					}
				}
			}
			
			//再把codes剩余的部分添加进去
			for (String code:codes) {
				if(!list.contains(code)){
					SvrRouteRule entity = new SvrRouteRule();
					entity.setServiceCode(code);
					entity.setGateLinkId(gateLinkId);
					entity.setStatus("1");
					entity.setRouteLevel("1");
					svrRouteRuleService.save(entity);
				}
			}
			
			
			msg = "路由设置成功！";
//			for (int i = 0; i < serviceCodes.length; i++) {
//				String serviceCode = serviceCodes[i];
//				List<SvrRouteRule> list = svrRouteRuleService.getByServiceCode(serviceCode,gateLinkId);
//				if (list.size() == 0 || list == null) {
//					//新增
//					SvrRouteRule entity = new SvrRouteRule();
//					entity.setServiceCode(serviceCode);
//					entity.setGateLinkId(gateLinkId);
//					entity.setStatus("1");
//					entity.setRouteLevel("1");
//					svrRouteRuleService.save(entity);
//				} else {
//					SvrRouteRule svrRouteRule = list.get(0);
//					svrRouteRule.setServiceCode(serviceCode);
//					svrRouteRule.setRouteLevel("1");
//					svrRouteRuleService.update(svrRouteRule);
//				}
//			}
		} catch (Exception e) {
			LOGGER.error("修改短信网关通道路由设置过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "路由设置失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 修改部分信息
	 * @param entity
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/updateByCallTest")
	Message updateByCallTest(GateDef entity){
		super.logType = SmLog.LOGTYPE_UPDATE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]修改短信网关通道";
		boolean isSuccess = true;
		String msg;
		try {
			List<Map<String, Object>> list = gateDefService.getGateLinkByGateLinkName(entity.getGateLinkName());
			if (list.size()>0) {
				isSuccess = false;
				msg = "短信通道名称有重复，请重新设置！";
			}else {
				gateDefService.updateByPrimaryKeySelective(entity);
				msg = "修改成功！";
			}
		} catch (Exception e) {
			LOGGER.error("修改短信网关通道信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "修改失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
}
